package com.example.springflowable.ask_for_leave.controller;

import io.swagger.annotations.ApiOperation;
import org.flowable.engine.IdentityService;
import org.flowable.engine.TaskService;
import org.flowable.idm.api.User;

import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;


/**
 * @Classname UserController
 * @Description TODO
 * @Date 2022/5/6 13:38
 * @Created by XiongXiong
 * @Author: X.I.O
 */
@RestController
@RequestMapping("/flowable")
public class UserController {

    @Autowired
    private TaskService taskService;

    @Autowired
    private IdentityService identityService;

    @ApiOperation("新建用户")
    @GetMapping(value = "/user/createUser", produces={"application/json"})
    public User createUser(String name, String firstName, String lastName){

        User user = identityService.newUser(name);
        user.setFirstName(firstName);
        user.setLastName(lastName);
        user.setEmail("123@qq.com");
        user.setPassword("123456");
        identityService.saveUser(user);
        return user;  //org.flowable.idm.api.User;
    }

    @ApiOperation("获取用户的任务")
    @GetMapping(value = "value=/getTasks/{userId}",produces={"application/json"})
    public List<Task> getTasks(@PathVariable String userId){
        //flowable:assignee="${userId}"
        return taskService.createTaskQuery().taskAssignee(userId).orderByTaskCreateTime().desc().list();
    }

    /**
     *  <exclusiveGateway id="decision"></exclusiveGateway>
     *     <sequenceFlow id="sequenceFlow-90e6eadb-3a9e-4955-bad4-ec337a360fac" sourceRef="decision" targetRef="false">
     *       <conditionExpression xsi:type="tFormalExpression"><![CDATA[${!approved}]]></conditionExpression>
     *     </sequenceFlow>
     * @param taskId
     * @return
     */
    @ApiOperation("审批不通过")
    @PostMapping("value=/faile/{taskId}")
    public String faile(@PathVariable String taskId){
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        if(task == null){
            return "流程不存在";
        }
        HashMap<String,Object> map = new HashMap<>();
        map.put("approved",false);
        taskService.complete(taskId,map);
        return "审批不通过";
    }

    /**
     * 审批通过
     */
    @PostMapping("/success/{taskId}")
    public String success(@PathVariable String taskId) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        if (task == null) {
            return "流程不存在";
        }
        //通过审核
        HashMap<String, Object> map = new HashMap<>();
        map.put("approved", true);
        taskService.complete(taskId, map);
        return "流程审核通过！";
    }















}
